/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package framework.config;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 *
 * @author du
 */
public class FileManager
{
    private static FileManager instance = null;
    FileWriter fw = null;

    public static FileManager getInstance()
    {
        if ( instance == null )
        {
            instance = new FileManager();
        }

        return instance;
    }

    private FileManager()
    {
        try
        {
            fw = new FileWriter( getErrorFile() );
                    //PropertiesManager.getInstance().getBoolean( "Util.deleteErrorFile", false ) );
        }
        
        catch( Exception e )
        {
            e.printStackTrace();
        }
    }

    /**
     * writeErrorLine
     *
     * @param error String
     */
    public void writeErrorLine( String error )
    {
        try
        {
            BufferedWriter bw = new BufferedWriter( fw );

            bw.write( error );
            bw.close();
        }

        catch( Exception e )
        {
            e.printStackTrace();
        }
    }

    /**
     * getConfigFile
     *
     * @return File
     */
    public File getConfigFile()
    {
        return makeFilePath( new File( getFolderPath() + "config.properties" ) );
    }

    /**
     * getErrorFile
     *
     * @return File
     */
    public File getErrorFile()
    {
        return makeFilePath( new File( getFolderPath() + "error.log" ) );
    }

    /**
     * getFolderPath
     *
     * @return String
     */
    private String getFolderPath()
    {
        return System.getProperty( "guest.workingPath", System.getProperty( "user.dir" ) ) + File.separator;
    }

    /**
     * makeFilePath
     *
     * @param file File
     * @return File
     */
    private File makeFilePath( File file )
    {
        try
        {
            if ( ! file.exists() )
            {
                File father = file.getParentFile();
                
                if ( ! father.exists() && ! father.isDirectory() )
                {
                    if ( ! father.mkdirs() )
                    {
                        throw new IOException( "Cannot create folder: " + father.getAbsolutePath() );
                    }
                }

                if ( ! file.createNewFile() )
                {
                    throw new IOException( "Cannot create file: " + file.getAbsolutePath() );
                }
            }
        }

        catch( Exception e )
        {
            Utilities.handleException( e );
        }

        return file;
    }
}
